$(document).ready(function() {
    // 分页相关变量
    var currentPage = 1;
    var rowsPerPage = 5;
    var allWarehouseData = [];
    var filteredWarehouseData = [];

    // API基础URL - 请根据实际部署情况修改
    const API_BASE_URL = 'http://localhost:5000/api';

    // ==================== 数据获取与渲染 ====================

    // 获取仓库列表
    function fetchWarehouses() {
        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/warehouses`,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    renderWarehouseTable(response.data);
                    initializeWarehouseData();
                    updateStatistics();
                } else {
                    showError('获取仓库列表失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    }

    // 渲染仓库表格
    function renderWarehouseTable(warehouses) {
        $('#warehouseTableBody').empty();

        if (warehouses.length === 0) {
            $('#warehouseTableBody').html('<tr><td colspan="10" class="text-center py-4">暂无仓库数据</td></tr>');
            return;
        }

        warehouses.forEach(warehouse => {
            const usagePercentage = warehouse.total_capacity > 0
                ? Math.floor((warehouse.current_capacity / warehouse.total_capacity) * 100)
                : 0;

            let usageClass = 'usage-bar-fill-normal';
            let statusClass = 'warehouse-status-normal';
            let statusText = warehouse.status || '正常';

            if (usagePercentage >= 90) {
                usageClass = 'usage-bar-fill-warning';
                statusClass = 'warehouse-status-warning';
                statusText = '即将满仓';
            } else if (usagePercentage >= 100) {
                usageClass = 'usage-bar-fill-danger';
                statusClass = 'warehouse-status-danger';
                statusText = '已满';
            }

            const row = `
                <tr>
                    <td>${warehouse.id}</td>
                    <td>${warehouse.name}</td>
                    <td>${warehouse.address}</td>
                    <td>${warehouse.total_capacity} 立方米</td>
                    <td>${warehouse.manager_id}</td>
                    <td>${warehouse.manager_name}</td>
                    <td>${Array.isArray(warehouse.products) ? warehouse.products.join(', ') : warehouse.products || '暂无商品'}</td>
                    <td>
                        <div class="usage-bar">
                            <div class="usage-bar-fill ${usageClass}" style="width: ${usagePercentage}%"></div>
                        </div>
                        <span class="usage-percentage">${usagePercentage}%</span>
                    </td>
                    <td><span class="warehouse-status ${statusClass}">${statusText}</span></td>
                    <td>
                        <button class="btn btn-sm btn-primary-custom">查看</button>
                        <button class="btn btn-sm btn-warning">编辑</button>
                        <button class="btn btn-sm btn-danger">删除</button>
                    </td>
                </tr>
            `;
            $('#warehouseTableBody').append(row);
        });
    }

    // ==================== CRUD 操作 ====================

    // 添加仓库
    $('#saveWarehouseBtn').click(function() {
        const warehouseData = {
            name: $('#warehouseName').val(),
            address: $('#warehouseAddress').val(),
            total_capacity: parseInt($('#warehouseCapacity').val()),
            manager_id: $('#warehouseManagerId').val(),
            manager_name: $('#warehouseManagerName').val(),
            products: $('#warehouseProducts').val().split(',').map(item => item.trim()),
            status: $('#warehouseStatus').val()
        };

        // 验证必填字段
        if (!validateWarehouseForm(warehouseData)) {
            return;
        }

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/warehouses`,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(warehouseData),
            success: function(response) {
                hideLoading();
                if (response.code === 201) {
                    showSuccess('仓库添加成功');
                    fetchWarehouses();
                    $('#addWarehouseModal').modal('hide');
                    $('#warehouseForm')[0].reset();
                } else {
                    showError('添加失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // 删除仓库
    $('#warehouseTableBody').on('click', '.btn-danger', function() {
        const warehouseId = $(this).closest('tr').find('td').eq(0).text();
        const warehouseName = $(this).closest('tr').find('td').eq(1).text();

        if (!confirm(`确定要删除仓库 ${warehouseName} (${warehouseId}) 吗？此操作不可撤销！`)) {
            return;
        }

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/warehouses/${warehouseId}`,
            method: 'DELETE',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('仓库删除成功');
                    fetchWarehouses();
                } else {
                    showError('删除失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // 编辑仓库 - 打开模态框
    $('#warehouseTableBody').on('click', '.btn-warning', function() {
        const $tr = $(this).closest('tr');
        const warehouseId = $tr.find('td').eq(0).text();

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/warehouses/${warehouseId}`,
            method: 'GET',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    const warehouse = response.data;
                    populateEditForm(warehouse);
                    $('#editWarehouseModal').modal('show');
                } else {
                    showError('获取仓库详情失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // 填充编辑表单
    function populateEditForm(warehouse) {
        $('#editWarehouseId').val(warehouse.id);
        $('#editWarehouseName').val(warehouse.name);
        $('#editWarehouseAddress').val(warehouse.address);
        $('#editWarehouseCapacity').val(warehouse.total_capacity);
        $('#editWarehouseManagerId').val(warehouse.manager_id);
        $('#editWarehouseManagerName').val(warehouse.manager_name);
        $('#editWarehouseProducts').val(
            Array.isArray(warehouse.products) ? warehouse.products.join(', ') : warehouse.products || ''
        );
        $('#editWarehouseRatio').val(
            warehouse.total_capacity > 0
                ? Math.floor((warehouse.current_capacity / warehouse.total_capacity) * 100)
                : 0
        );
        $('#editWarehouseStatus').val(warehouse.status || '正常');
    }

    // 更新仓库
    $('#saveEditWarehouseBtn').click(function() {
        const warehouseId = $('#editWarehouseId').val();
        const warehouseData = {
            name: $('#editWarehouseName').val(),
            address: $('#editWarehouseAddress').val(),
            total_capacity: parseInt($('#editWarehouseCapacity').val()),
            current_capacity: parseInt($('#editWarehouseCapacity').val()) * (parseInt($('#editWarehouseRatio').val()) / 100),
            manager_id: $('#editWarehouseManagerId').val(),
            manager_name: $('#editWarehouseManagerName').val(),
            products: $('#editWarehouseProducts').val().split(',').map(item => item.trim()),
            status: $('#editWarehouseStatus').val()
        };

        // 验证必填字段
        if (!validateWarehouseForm(warehouseData)) {
            return;
        }

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/warehouses/${warehouseId}`,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(warehouseData),
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('仓库更新成功');
                    fetchWarehouses();
                    $('#editWarehouseModal').modal('hide');
                } else {
                    showError('更新失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // ==================== 批量操作 ====================

    // 批量导入
    $('#importWarehousesBtn').click(function() {
        const fileInput = $('#importFile')[0];
        const file = fileInput.files[0];

        if (!file) {
            showError('请选择要导入的CSV文件！');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/warehouses/import`,
            method: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                hideLoading();
                if (response.code === 201) {
                    showSuccess(`成功导入 ${response.data.count} 个仓库`);
                    fetchWarehouses();
                    $('#importWarehouseModal').modal('hide');
                    $('#importFile').val('');
                } else {
                    showError('导入失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // 数据清理
    $('#dataCleanBtn').click(function() {
        if (!confirm('确认要清理所有仓库数据吗？此操作不可恢复，且会删除所有仓库信息！')) {
            return;
        }

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/warehouses/clean`,
            method: 'DELETE',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('所有仓库数据已清理完毕');
                    fetchWarehouses();
                    $('#dataCleanModal').modal('hide');
                } else {
                    showError('清理失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // ==================== 辅助函数 ====================

    // 验证仓库表单
    function validateWarehouseForm(data) {
        if (!data.name || !data.address || isNaN(data.total_capacity) ||
            !data.manager_id || !data.manager_name) {
            showError('请填写所有必填字段！');
            return false;
        }

        if (data.total_capacity <= 0) {
            showError('仓库容量必须大于0');
            return false;
        }

        return true;
    }

    // 显示加载状态
    function showLoading() {
        $('#loadingOverlay').removeClass('hidden');
    }

    // 隐藏加载状态
    function hideLoading() {
        $('#loadingOverlay').addClass('hidden');
    }

    // 显示成功消息
    function showSuccess(message) {
        $('#alertSuccess').text(message).removeClass('hidden');
        setTimeout(() => $('#alertSuccess').addClass('hidden'), 3000);
    }

    // 显示错误消息
    function showError(message) {
        $('#alertError').text(message).removeClass('hidden');
        setTimeout(() => $('#alertError').addClass('hidden'), 5000);
    }

    // ==================== 分页与筛选功能 ====================

    // 初始化仓库数据
    function initializeWarehouseData() {
        allWarehouseData = [];
        $('#warehouseTableBody tr').each(function(index) {
            const $row = $(this);
            allWarehouseData.push({
                element: this,
                id: $row.find('td').eq(0).text(),
                name: $row.find('td').eq(1).text(),
                address: $row.find('td').eq(2).text(),
                capacity: $row.find('td').eq(3).text(),
                managerId: $row.find('td').eq(4).text(),
                managerName: $row.find('td').eq(5).text(),
                products: $row.find('td').eq(6).text(),
                usage: $row.find('.usage-percentage').text(),
                status: $row.find('.warehouse-status').text(),
                region: getRegionFromAddress($row.find('td').eq(2).text())
            });
        });
        filteredWarehouseData = [...allWarehouseData];
        updateTable();
    }

    // 根据地址判断区域
    function getRegionFromAddress(address) {
        if (address.includes('北京')) return '华北';
        if (address.includes('上海')) return '华东';
        if (address.includes('广州')) return '华南';
        if (address.includes('深圳')) return '华南';
        if (address.includes('成都')) return '西南';
        if (address.includes('重庆')) return '西南';
        return '其他';
    }

    // 更新表格显示
    function updateTable() {
        // 隐藏所有行
        allWarehouseData.forEach(warehouse => {
            $(warehouse.element).hide();
        });

        // 显示当前页的行
        const startIndex = (currentPage - 1) * rowsPerPage;
        const endIndex = startIndex + rowsPerPage;
        const warehousesToShow = filteredWarehouseData.slice(startIndex, endIndex);

        warehousesToShow.forEach(warehouse => {
            $(warehouse.element).show();
        });

        // 更新分页信息
        updatePaginationInfo();
    }

    // 渲染分页按钮
    function renderPaginationButtons() {
        const totalPages = Math.ceil(filteredWarehouseData.length / rowsPerPage);
        const paginationContainer = $('.pagination-buttons');
        paginationContainer.empty();

        // 最多显示5个页码按钮
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);

        if (currentPage <= 3) {
            endPage = Math.min(5, totalPages);
        }
        if (currentPage >= totalPages - 2) {
            startPage = Math.max(1, totalPages - 4);
        }

        // 第一页按钮
        if (startPage > 1) {
            const firstBtn = $('<button>').text('1').addClass('btn btn-page');
            firstBtn.on('click', () => goToPage(1));
            paginationContainer.append(firstBtn);

            if (startPage > 2) {
                paginationContainer.append($('<span>').text('...').addClass('px-2'));
            }
        }

        // 中间页码按钮
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = $('<button>').text(i).addClass('btn btn-page');
            if (i === currentPage) {
                pageBtn.addClass('bg-blue-500 text-white');
            }
            pageBtn.on('click', () => goToPage(i));
            paginationContainer.append(pageBtn);
        }

        // 最后一页按钮
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationContainer.append($('<span>').text('...').addClass('px-2'));
            }

            const lastBtn = $('<button>').text(totalPages).addClass('btn btn-page');
            lastBtn.on('click', () => goToPage(totalPages));
            paginationContainer.append(lastBtn);
        }
    }

    // 更新分页信息
    function updatePaginationInfo() {
        const totalPages = Math.ceil(filteredWarehouseData.length / rowsPerPage);
        const totalRecords = filteredWarehouseData.length;
        $("#currentPageInfo").text(`当前第 ${currentPage} 页，共 ${totalPages} 页，总计 ${totalRecords} 条记录`);
        renderPaginationButtons();
    }

    // 上一页
    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            updateTable();
        }
    }

    // 下一页
    function nextPage() {
        const totalPages = Math.ceil(filteredWarehouseData.length / rowsPerPage);
        if (currentPage < totalPages) {
            currentPage++;
            updateTable();
        }
    }

    // 跳转到指定页
    function goToPage(page) {
        const totalPages = Math.ceil(filteredWarehouseData.length / rowsPerPage);
        if (page >= 1 && page <= totalPages) {
            currentPage = page;
            updateTable();
        }
    }

    // 筛选功能
    function filterWarehouses() {
        const regionFilter = $('#region-filter').val();
        const statusFilter = $('#status-filter').val();

        filteredWarehouseData = allWarehouseData.filter(warehouse => {
            // 区域筛选
            const regionMatch = regionFilter === '全部' || warehouse.region === regionFilter;

            // 状态筛选
            const statusMatch = statusFilter === '全部' || warehouse.status === statusFilter;

            return regionMatch && statusMatch;
        });

        // 重置到第一页
        currentPage = 1;
        updateTable();
    }

    // 重置筛选
    function resetFilters() {
        $('#region-filter').val('全部');
        $('#status-filter').val('全部');
        filteredWarehouseData = [...allWarehouseData];
        currentPage = 1;
        updateTable();
    }

    // 搜索功能
    function applySearch() {
        const searchText = $('.search-bar input').val().toLowerCase().trim();

        if (!searchText) {
            filteredWarehouseData = [...allWarehouseData];
        } else {
            filteredWarehouseData = allWarehouseData.filter(warehouse => {
                // 检查所有可搜索字段
                return (
                    warehouse.id.toLowerCase().includes(searchText) ||
                    warehouse.name.toLowerCase().includes(searchText) ||
                    warehouse.address.toLowerCase().includes(searchText) ||
                    warehouse.managerId.toLowerCase().includes(searchText) ||
                    warehouse.managerName.toLowerCase().includes(searchText) ||
                    warehouse.products.toLowerCase().includes(searchText)
                );
            });
        }

        // 重置到第一页
        currentPage = 1;
        updateTable();
    }

    // 防抖函数
    function debounce(func, wait) {
        let timeout;
        return function() {
            const context = this, args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(context, args);
            }, wait);
        };
    }

    // 更新统计信息
    function updateStatistics() {
        const warehouseCount = allWarehouseData.length;
        $('.stat-value').first().text(warehouseCount);

        // 计算平均使用率
        let totalUsage = 0;
        let warehouseWithUsage = 0;

        $('#warehouseTableBody tr').each(function() {
            const usageText = $(this).find('.usage-percentage').text();
            const usage = parseInt(usageText);
            if (!isNaN(usage)) {
                totalUsage += usage;
                warehouseWithUsage++;
            }
        });

        const avgUsage = warehouseWithUsage > 0 ? Math.round(totalUsage / warehouseWithUsage) : 0;
        $('.stat-value').eq(1).text(avgUsage + '%');
    }

    // 查看按钮点击事件
    $('#warehouseTableBody').on('click', '.btn-primary-custom', function() {
        const $tr = $(this).closest('tr');
        const warehouseId = $tr.find('td').eq(0).text();
        const warehouseName = $tr.find('td').eq(1).text();
        const warehouseAddress = $tr.find('td').eq(2).text();
        const warehouseCapacity = $tr.find('td').eq(3).text();
        const managerId = $tr.find('td').eq(4).text();
        const managerName = $tr.find('td').eq(5).text();
        const products = $tr.find('td').eq(6).text();
        const ratio = $tr.find('.usage-percentage').text();
        const status = $tr.find('.warehouse-status').text();

        $('#viewWarehouseId').text(warehouseId);
        $('#viewWarehouseName').text(warehouseName);
        $('#viewWarehouseAddress').text(warehouseAddress);
        $('#viewWarehouseCapacity').text(warehouseCapacity);
        $('#viewWarehouseManagerId').text(managerId);
        $('#viewWarehouseManagerName').text(managerName);
        $('#viewWarehouseProducts').text(products);
        $('#viewWarehouseRatio').text(ratio);
        $('#viewWarehouseStatus').text(status);

        $('#viewWarehouseModal').modal('show');
    });

    // ==================== 事件绑定 ====================

    // 绑定筛选按钮事件
    $('.filter-bar .btn-primary-custom').on('click', filterWarehouses);
    $('.filter-bar .btn-secondary-custom').on('click', resetFilters);

    // 绑定搜索事件（带防抖）
    const debouncedSearch = debounce(applySearch, 300);
    $('.search-bar input').on('input', debouncedSearch);

    // 点击搜索图标也可以触发搜索
    $('.search-bar .fa-search').parent().on('click', applySearch);

    // 按回车键触发搜索
    $('.search-bar input').on('keypress', function(e) {
        if (e.which === 13) applySearch();
    });

    // 初始化页面
    fetchWarehouses();
});